package com.superjson.showpro.service.impl;

import com.beantools.util.CollectionUtil;
import com.superjson.showpro.base.GenericServiceImpl;
import com.superjson.showpro.dao.AttachDao;
import com.superjson.showpro.entity.Attach;
import com.superjson.showpro.service.AttachService;
import com.superjson.showpro.shared.enums.FileTypeEnum;
import com.superjson.showpro.shared.result.Result;
import com.superjson.showpro.shared.result.ResultUtil;
import com.superjson.showpro.shared.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

import static com.beantools.constants.SingleChar.EN_POINT;
import static com.beantools.util.ObjectUtil.isNull;
import static com.superjson.showpro.shared.enums.FileTypeEnum.FILE_TYPE_COMMON;
import static com.superjson.showpro.shared.enums.FileTypeEnum.FILE_TYPE_JAR;
import static com.superjson.showpro.shared.util.CommonUtil.getTomcatRootPath;
import static com.superjson.showpro.shared.util.CommonUtil.ifTrueThrow;

/**
 * Created By zby on 21:50 2019/5/28
 */
@Service
public class AttachServiceImpl extends GenericServiceImpl<Attach> implements AttachService {

    private AttachDao attachDao;

    @Value("#{attachConf[fileUploadRootPath]}")
    private String fileUploadRootPath;

    @Autowired
    public AttachServiceImpl(AttachDao attachDao) {
        super(attachDao);
        this.attachDao = attachDao;
    }

    @Override
    public Result<Attach> saveAttach(MultipartFile file, String originalFilename, Date date, String name, String relativePath, String description, FileTypeEnum fileType) {
        Attach attach = new Attach();
        long size = file.getSize();
        attach.setRelativeFolder(getTomcatRootPath() + "/" + fileUploadRootPath);
        attach.setOriginalName(originalFilename);
        String suffixName = null;
        String prefixName = null;
        if (originalFilename.contains(EN_POINT)) {
            suffixName = originalFilename.substring(originalFilename.lastIndexOf(EN_POINT) + 1, originalFilename.length());
            prefixName = originalFilename.substring(0, originalFilename.lastIndexOf(EN_POINT));
        }
        attach.setOriginalName(originalFilename);
        attach.setName(name);
        attach.setSuffixName(suffixName);
        attach.setPrefixName(prefixName);
        attach.setSize(size);
        attach.setDescription(description);
        attach.setRelativePath(relativePath);
        attach.setUpLoadTime(date);
        attach.setType(isNull(fileType) ? (name.contains(".jar") ? FILE_TYPE_JAR : FILE_TYPE_COMMON) : fileType);
        Attach dbAttach = attachDao.save(attach);
        return ResultUtil.buildSuccess(dbAttach);
    }
}
